package com.dlc.shop.delivery.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.common.constants.DeliveryCacheNames;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.delivery.common.dao.PrinterMapper;
import com.dlc.shop.delivery.common.model.Printer;
import com.dlc.shop.delivery.common.service.PrinterService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 打印机
 * @author TRACK
 */
@Service
@AllArgsConstructor
public class PrinterServiceImpl extends ServiceImpl<PrinterMapper, Printer> implements PrinterService {

    private final PrinterMapper printerMapper;

    @Override
    public void insert(Printer printer) {
        checkInfo(printer);
        printerMapper.insert(printer);
    }

    @Override
    public void update(Printer printer) {
        checkInfo(printer);
        printerMapper.updateById(printer);
    }

    private void checkInfo(Printer printer) {
        if (Objects.nonNull(printer.getPrinterId())) {
            Printer dbPrinter = printerMapper.selectById(printer.getPrinterId());
            if (!Objects.equals(dbPrinter.getShopId(), printer.getShopId())) {
                throw new YamiShopBindException("yami.operate.auth");
            }
        }
        int count = printerMapper.countByName(printer.getShopId(), printer.getPrinterName(), printer.getPrinterId());
        if (count > 0) {
            // 设备名称已存在
            throw new YamiShopBindException("yami.print.name.is.exist");
        }
    }

    @Override
    public void setDefault(Long printerId) {
        Printer printer = getById(printerId);
        if (Objects.isNull(printer)) {
            // 设备不存在
            throw new YamiShopBindException("yami.print.is.not.exist");
        }
        if (Objects.equals(printer.getIsDefault(), 0)) {
            // 设为默认
            printerMapper.cancelDefault(printer.getShopId());
        }
        printerMapper.setDefault(printerId);
    }

    @Override
    @Cacheable(cacheNames = DeliveryCacheNames.PRINTER_LIST_KEY, key = "#shopId")
    public List<Printer> listByShopId(Long shopId) {
        return printerMapper.listByShopId(shopId);
    }

    @Override
    @CacheEvict(cacheNames = DeliveryCacheNames.PRINTER_LIST_KEY, key = "#shopId")
    public void removeCache(Long shopId) {

    }
}
